package com.qdlc.p2p.manage.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.NoticeService;
import com.qdlc.p2p.biz.service.OperatorRoleService;
import com.qdlc.p2p.biz.service.OperatorService;
import com.qdlc.p2p.biz.service.RoleService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.code.MD5;
import com.qdlc.p2p.dal.common.NoticeTypeHelper;
import com.qdlc.p2p.dal.common.NoticeTypeHelper.NidType;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Notice;
import com.qdlc.p2p.dal.dto.NoticeType;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.OperatorRole;
import com.qdlc.p2p.dal.dto.Role;
import com.qdlc.p2p.dal.model.OperatorModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

public class OperatorAction extends BaseAction<Operator> implements ModelDriven<Operator> {

	@Resource
	private OperatorService operatorService;
	@Resource
	private RoleService roleService;
	@Resource
	private OperatorRoleService userRoleService;
	@Resource
	private NoticeService noticeService;

	private Map<String, Object> data;

	@Action(value = "/modules/login")
	public void login() throws Exception {
		data = new HashMap<String, Object>();
		String userName = this.paramString("userName");
		String password = this.paramString("password");
		Operator operator = operatorService.login(userName, password);
		if (operator != null && operator.getUserName() != null) {
			session.put(Constant.SESSION_OPERATOR, operator);
			
			operator.setLoginTime(DateUtil.getNow());
			operator.setLoginIp(getRequestIp());
			operatorService.userUpdate(operator);
			
			data.put("result", true);
			printJson(getStringOfJpaObj(data));
		}
	}

	/**
	 * 退出系统
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/logout")
	public void logout() throws Exception {
		session.put(Constant.SESSION_OPERATOR, null);
		data = new HashMap<String, Object>();
		data.put("result", true);
		data.put("msg", "退出系统成功！");
		data.put("manage_url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.MANAGE_URL));
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 修改密码
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/general/userEditPwd")
	public void userEditPwd() throws Exception {
		data = new HashMap<String, Object>();
		OperatorModel managerModel = OperatorModel.instance(model);
		String operatorUserName = getOperatorUserName();
		managerModel.validModifyPwdUsername(operatorUserName);
		managerModel.setOldPassword(this.paramString("oldPassword"));
		managerModel.setConfirmPassword(this.paramString("confirmPassword"));
		Operator manager = operatorService.getUserByUserName(operatorUserName);
		managerModel.validModifyPwdModel(manager);
		manager.setUpdateManager(getOperatorUserName());
		manager.setPwd(MD5.encode(managerModel.getPwd()));
		operatorService.updateUserPwd(manager);
		data.put("result", true);
		data.put("msg", "修改密码成功！");
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 重置用户密码
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorResetPwd")
	public void operatorResetPwd() throws Exception {
		data = new HashMap<String, Object>();
		long id = this.paramLong("id");
		Operator operator = operatorService.getUserById(id);
		operator.setUpdateManager(getOperatorUserName());
		// 生成随机8位密码
		String password = StringUtil.getRandomString(8);
		operator.setPwd(MD5.encode(password));
		operatorService.updateUserPwd(operator);
		data.put("result", true);
		data.put("msg", "重置密码成功！");
		//发送密码至用户
		//充值密码短信模版
		String noticeTypeNid = NoticeTplNid.NOTICE_OPERATOR_PASSWORD_RESET;
		
		Map<String,Object> sendData = new HashMap<String,Object>();
		//获取 注册验证码 短信模版内容
		NoticeType smsType = NoticeTypeHelper.getValue(noticeTypeNid, NidType.NOTICE_SMS);
		sendData.put("password", password);
		sendData.put("phone", operator.getPhone());
		sendData.put("operator", operator);
		sendData.put("webname", SystemConfigs.WEB_NAME);
		if (smsType.getSend() == NoticeTplNid.NOTICE_SEND) {
			//封装notice类
			Notice notice = new Notice();
			notice.setNid(noticeTypeNid);
			notice.setType(String.valueOf(NoticeTplNid.NOTICE_SMS));
			notice.setReceiveAddr(operator.getPhone());
			notice.setContent(StringUtil.fillTemplet(smsType.getTemplet(), sendData));
			notice.setAddTime(DateUtil.getNow());
			//发送短信方法
			noticeService.sendNotice(notice);
		}
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 用户管理页面
	 * 
	 * @return 页面
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorManager")
	public String operatorManager() throws Exception {
		return "operatorManager";
	}

	/**
	 * 用户查询列表
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorList")
	public void operatorList() throws Exception {
		data = new HashMap<String, Object>();
		int pageNumber = paramInt("page"); // 当前页数
		int pageSize = paramInt("rows"); // 每页每页总数
		PageDataList<Operator> userList = operatorService.getUserPageList(pageNumber, pageSize, searchName, model);
		data.put("total", userList.getPage().getTotal()); // 总行数
		data.put("rows", userList.getList()); // 集合对象
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 用户添加页面
	 * 
	 * @return 页面
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorAddPage")
	public String operatorAddPage() throws Exception {
		List<Role> roleList = roleService.getRoleList();
		request.setAttribute("roleList", roleList);
		return "operatorAddPage";
	}

	/**
	 * 用户添加
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorAdd")
	public void operatorAdd() throws Exception {
		data = new HashMap<String, Object>();
		String[] roleIdArr = request.getParameterValues("roleId");
		if (roleIdArr == null) {
		    throw new BusinessException("请选择一个用户角色", 1);
		}
		OperatorModel userModel = OperatorModel.instance(model);
		userModel.setConfirmPassword(paramString("confirmPassword"));
		userModel.validLoginModel();
		userModel.validRegModel();
		model.setAddManager(getOperatorUserName());
		model.setUpdateManager(getOperatorUserName());
		operatorService.addOperator(model, roleIdArr);

		data.put("result", true);
		data.put("msg", "用户添加成功！");
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 用户修改页面
	 * 
	 * @return 页面
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorEditPage")
	public String operatorEditPage() throws Exception {
		long id = this.paramLong("id");
		Operator operator = operatorService.getUserById(id);
		List<OperatorRole> userRoleList = userRoleService.getUserRoleList(id);
		List<Role> roleList = roleService.getRoleList();
		request.setAttribute("roleList", roleList);
		request.setAttribute("operatorRoleList", userRoleList);
		request.setAttribute("operator", operator);
		ActionContext.getContext().getValueStack().push(operator);
		return "operatorEditPage";
	}

	/**
	 * 用户修改
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorEdit")
	public void operatorEdit() throws Exception {
		data = new HashMap<String, Object>();
		String[] roleIdArr = request.getParameterValues("roleId");
		if (roleIdArr == null) {
			throw new BusinessException("请选择一个用户角色", 1);
		}
		operatorService.userUpdate(model, roleIdArr);
		data.put("result", true);
		data.put("msg", "用户修改成功！");
		printJson(getStringOfJpaObj(data));
	}

	/**
	 * 用户禁用或启用
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/operatorDelete")
	public void operatorDelete() throws Exception {
		operatorService.updateStatus(model.getId(), model.getStatus());
		printWebSuccess();
	}

	/**
	 * ajax请求验证用户
	 * 
	 * @throws Exception 异常
	 */
	@Action(value = "/modules/system/operator/checkOperator")
	public void checkOperator() throws Exception {
		data = new HashMap<String, Object>();
		String userName = paramString("userName");
		Operator manager = operatorService.getUserByUserName(userName);
		if (manager != null) {
			data.put("data", manager);
			data.put("result", true);
			printJson(getStringOfJpaObj(data));
		} else {
			data.put("result", false);
			printJson(getStringOfJpaObj(data));
		}
	}

}
